package com.anhry.app.safety.manage.zczb.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.anhry.app.safety.manage.enterprise.bean.TbCorpType;
import com.anhry.app.safety.manage.system.bean.TbUser;
import com.anhry.app.safety.manage.zczb.bean.TbZczbBzhInfo;
import com.anhry.app.safety.manage.zczb.bean.TbZczbBzhTable;
import com.anhry.app.safety.manage.zczb.bean.TbZczbBzhType;
import com.anhry.app.safety.manage.zczb.struts.base.ZczbBaseAction;
import com.anhry.app.safety.util.Loggers;
import com.anhry.app.safety.util.Page;
import com.anhry.app.safety.util.UploadFile;
import com.anhry.app.safety.util.Util;
import com.anhry.app.safety.util.UtilMethod;
import com.anhry.app.safety.util.bean.Permission;

/**
 * @date:2012-9-20
 * @remark:
 * @author:dongbin
 */

@Controller
@Scope("prototype")
@SuppressWarnings("unchecked")
public class ZczbBzhAction extends ZczbBaseAction{
	private static Logger logger = Logger.getLogger(ZczbBzhAction.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private File dbFile;
	private String dbFileContentType;
	private String dbFileFileName;
	private String fileTypes;
	private String objIds;
	private List haveList;
	private String itemXml;
	
	/**
	 * 标准列表
	 * @return
	 */
	
	@Permission(module = "zczb_bzh", permissionVaule = 1)
	public String list(){
		int rowCount = 0;
		int num = (this.num != null && !"".equals(this.num ))?Integer.parseInt(this.num ):1;
		int size = (this.size != null && !"".equals(this.size ))?Integer.parseInt(this.size ):10;
		try {
			String orderHql = " order by t.id";//排序hql语句
			String hql = this.getQuaryHql();
			List objSize = this.utilService.getObjecList("TbZczbBzhTable", hql,null,0,0);
			if(objSize != null && objSize.size() > 0){
				rowCount = Integer.parseInt(objSize.get(0).toString());
			}
			Page page = new Page(size,num,rowCount);
			this.setPage(page);
			this.setObjList(this.utilService.getObjecList("TbZczbBzhTable", hql,orderHql,page.getStartRow(),page.getSize()));
			this.setResult("bzh_list");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("zczb: ZczbBzhAction:list()异常："+e.getMessage());
		}
		return ERROR;
	}
	
	/**
	 * 标准导入页面
	 * @return
	 */
	@Permission(module = "zczb_bzh", permissionVaule = 0)
	public String add(){
		try {
			this.setTypeList((List)this.utilService.getHqlQuery("from TbCorpType t where 1=1 and t.isDele=0 and t.id<>0 and t.typeParentId<>0 order by t.typeParentId,t.id"));
			this.setResult("bzh_add");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("zczb: ZczbBzhAction:add()异常："+e.getMessage());
		}
		return ERROR;
	}
	/**
	 * 标准重新导入页面
	 * @return
	 */
	@Permission(module = "zczb_bzh", permissionVaule = 2)
	public String update(){
		try {
			this.setKeyWord(this.contextPvd.decodeAndEncode(this.keyWord));
			if(null!=this.objId && this.objId.length()>0){
				TbZczbBzhTable tab = (TbZczbBzhTable)this.utilService.getObjectById(TbZczbBzhTable.class, Long.parseLong(this.objId));
				if(null!=tab){
					this.setTab(tab);
					this.setTypeList((List)this.utilService.getHqlQuery("from TbCorpType t where 1=1 and t.isDele=0 and t.id<>0 and t.typeParentId<>0 and (t.hiddenTabId<>"+tab.getId()+" or t.hiddenTabId is null) order by t.typeParentId,t.id"));
					this.setHaveList((List)this.utilService.getHqlQuery("from TbCorpType t where 1=1 and t.isDele=0 and t.hiddenTabId in("+tab.getId()+") order by t.typeParentId,t.id"));
					if("1".equals(this.forward)){
						this.setResult("bzh_reupdate");
					}else{
						this.setResult("bzh_update");
					}
					return SUCCESS;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("zczb: ZczbBzhAction:add()异常："+e.getMessage());
		}
		this.setTip(Util.NOTIP);
		return ERROR;
	}
	
	/**
	 * 删除标准
	 * @return
	 */
	public String delete(){
		try {
			this.setKeyWord(this.contextPvd.decodeAndEncode(this.keyWord));
			if(null!=this.objId && this.objId.length()>0){
				TbZczbBzhTable tab = (TbZczbBzhTable)this.utilService.getObjectById(TbZczbBzhTable.class, Long.parseLong(this.objId));
				if(null!=tab){
					TbUser user = (TbUser)this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
					this.utilService.deleteBySql("update tb_corp_type t set t.hidden_tab_id='',t.hidden_tab_name='' where t.hidden_tab_id="+tab.getId());
					this.utilService.deleteBySql("delete tb_zczb_bzh_info t where t.tab_id="+tab.getId());
					UploadFile.removeFile(Util.SAFETY_FILE+File.separator+tab.getTabPath());//将原文件删除
					this.utilService.deleteBySql("delete from TB_ZCZB_BZH_TABLE t where t.id = " + tab.getId());
					this.utilService.saveActionLog(user, "删除自查标准表 ---- " + tab.getTabName());
					this.tip = "操作成功!";
				} else {
					this.tip = "标准不存在!";
				}
			} 
			return this.list();
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("zczb: ZczbBzhAction:look()异常："+e.getMessage());
		}
		return ERROR;
	}
	
	/**
	 * 标准导入保存
	 * @return
	 */
	public String save(){
		try {
			if(this.dbFile == null || !this.dbFile.exists()){
				this.setTip("附件不能为空！");
				return this.add();
			}
			if(!UtilMethod.filterType( this.getDbFileContentType(), this.getFileTypes().split(","))){
				this.setTip("附件格式错误！");
				return this.add();
			}
			
			TbUser user = (TbUser)this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
			
			//进入导入程序 
			long start = new Date().getTime();
			File file = this.dbFile;
			InputStream is = new FileInputStream(file.getPath());
	        Workbook rwb = Workbook.getWorkbook(is);	//声名一个工作薄
	        Sheet st = rwb.getSheet(0);	//第0个工作表
	        int Rows=st.getRows();
	        int Cols=st.getColumns();
	        if(Rows < 2 || Cols != 6){
            	this.setTip("Excel格式错误，excel总行数为："+Rows+" 总列数为："+Cols+"！");
            	return "tips";
            }
	        
	        //自查自报标准表
	        TbZczbBzhTable tab = null;
	        boolean exists = false;
			if(null!=this.objId && this.objId.length()>0){
				tab = (TbZczbBzhTable)this.utilService.getObjectById(TbZczbBzhTable.class, Long.parseLong(this.objId));
				if(null!=tab){
					this.utilService.deleteBySql("delete tb_zczb_bzh_info t where t.tab_id="+tab.getId());//将原导入的数据删除
					exists = true;
				}
			}else{
				tab = new TbZczbBzhTable();
			}
			
			tab.setIsDele("0");
			tab.setTabFileName(this.dbFileFileName);	//文件名
			String tabName = st.getCell(0, 0).getContents();
			if(tabName != null && !"".equals(tabName)){
				tab.setTabName(tabName.trim());
			}
			UploadFile.removeFile(Util.SAFETY_FILE+File.separator+tab.getTabPath());//将原文件删除
			tab.setTabTime(new Date());
			String path = Util.SAFETY_FILE+File.separator+Util.FILE_FOLDER+File.separator+Util.ZCZB_STANDARD;
			String fileName = UploadFile.copy2(this.dbFile, path, this.dbFileFileName);
			String path1 = Util.FILE_FOLDER+File.separator+Util.ZCZB_STANDARD+File.separator+fileName;
			tab.setTabPath(path1);
			this.utilService.saveOrUpdate(tab);
			
			this.utilService.saveActionLog(user, "隐患排查Excel数据导入：是否为覆盖："+exists+" 当前文件名："+this.dbFileFileName+" 当前工作表的名字："+st.getName()+" 自查表名："+tabName+" 总行数:"+Rows+"总列数:"+Cols);
			
			String type1 = null;
			TbZczbBzhType type2 = null;
			String type3 = null;
			String type4 = null;
			TbZczbBzhInfo info = null;
			for(int i=2;i<Rows;i++){//从第3行开始
				if(st.getCell(0, i).getContents() != null && !"".equals(st.getCell(0, i).getContents())){		//1级隐患类型,第0列
					type1 = this.getType1(st.getCell(0, i).getContents().trim());
				}
				if(logger.isDebugEnabled()) {
					logger.debug("type1 = " + type1 + ", row = " + i);
				}
				if(st.getCell(1, i).getContents() != null && !"".equals(st.getCell(1, i).getContents())){		//2级隐患类型,第1列
					type2 = this.zczbService.getBzhType(st.getCell(1, i).getContents().trim());
				}
				if(logger.isDebugEnabled()) {
					logger.debug("type2 = " + type2 + ", row = " + i);
				}
				if(st.getCell(2, i).getContents() != null && !"".equals(st.getCell(2, i).getContents())){		//3级隐患类型,第2列
					type3 = st.getCell(2, i).getContents().trim();
				}
				if(logger.isDebugEnabled()) {
					logger.debug("type3 = " + type3 + ", row = " + i);
				}
				if(st.getCell(3, i).getContents() != null && !"".equals(st.getCell(3, i).getContents())){		//4级隐患类型,第3列
					type4 = st.getCell(3, i).getContents().trim();
				}
				if(st.getCell(4, i).getContents() != null && !"".equals(st.getCell(4, i).getContents())){		//自查内容，第4列
					info = new TbZczbBzhInfo();
					info.setInfoContent(st.getCell(4, i).getContents());
					info.setInfoSort(i);
					info.setInfoType1(Long.parseLong(type1));
					if(null!=type2){
						info.setInfoType2(type2.getId());
					}
					info.setInfoType3(type3);
					info.setInfoType4(type4);
					info.setInfoYj(st.getCell(5, i).getContents());
					info.setIsDele("0");
					info.setTabId(tab.getId());
					this.utilService.save(info);
				}
				
			}
			rwb.close();
			
			//先将原对应关系清除
			this.utilService.deleteBySql("update tb_corp_type t set t.hidden_tab_id='',t.hidden_tab_name='' where t.hidden_tab_id="+tab.getId());
			if(null!=this.objIds && this.objIds.length()>0){
				String[] arry = this.objIds.split(",");
				for(int i=0;i<arry.length;i++){
					TbCorpType type = (TbCorpType)this.utilService.getObjectById(TbCorpType.class, Long.parseLong(arry[i]));
					if(null!=type){
						type.setHiddenTabId(tab.getId());
						type.setHiddenTabName(tab.getTabName());
						this.utilService.update(type);
					}
				}
			}
			
			long end = new Date().getTime();
	        this.utilService.saveActionLog(user, tab.getTabName()+"导入成功！所用的时间:"+(end-start)/1000+"秒");
	        if(exists){
	        	this.setTip("重新导入成功！所用时间："+(end-start)/1000+"秒");
	        }else{
	        	this.setTip("导入成功！所用时间："+(end-start)/1000+"秒");
	        }
			return this.list();
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("zczb: ZczbBzhAction:save()异常："+e.getMessage());
		}
		return ERROR;
	}
	
	public void validateAttachment(){
		tip = null;
		getContextPvd().getResponse().setCharacterEncoding("GBK");
		try {
			if(this.dbFile == null || !this.dbFile.exists()){
				this.setTip("附件不能为空！");
				getContextPvd().getResponse().getWriter().print(getContextPvd().encode(tip));
				
				return; 
			}
			if(!UtilMethod.filterType( this.getDbFileContentType(), this.getFileTypes().split(","))){
				this.setTip("附件格式错误！只能上传文件扩展名为.xls的Excel文件!");
				getContextPvd().getResponse().getWriter().print(tip);
				return; 
			}
			
			File file = this.dbFile;
			InputStream is = new FileInputStream(file.getPath());
	        Workbook rwb = Workbook.getWorkbook(is);	//声名一个工作薄
	        Sheet st = rwb.getSheet(0);	//第0个工作表
	        int Rows=st.getRows();
	        int Cols=st.getColumns();
	        if(Rows < 2 || Cols != 6){
            	this.setTip("Excel格式错误，excel总行数为："+Rows+" 总列数为："+Cols+"！");
            	getContextPvd().getResponse().getWriter().print(tip);
				return; 
            }
			
			for(int i=2;i<Rows;i++){//从第3行开始
		 	if(st.getCell(0, i).getContents() == null || "".equals(st.getCell(0, i).getContents())){		//1级隐患类型,第0列
		 		tip = "I 级隐患 (第 " + (i + 1) +  "行 第 1 列) 不能为空.";
				getContextPvd().getResponse().getWriter().print(tip);
				rwb.close();
				return; 
				}
				if(st.getCell(1, i).getContents() == null || "".equals(st.getCell(1, i).getContents())){		//2级隐患类型,第1列
					tip = "II 级隐患 (第 " + (i + 1) +  "行 第 2 列) 不能为空.";
					getContextPvd().getResponse().getWriter().print(tip);
					rwb.close();
					return; 
				}
				if(st.getCell(2, i).getContents() == null || "".equals(st.getCell(2, i).getContents())){		//3级隐患类型,第2列
					tip ="III 级隐患 (第 " + (i + 1) +  "行 第 3 列) 不能为空.";
					getContextPvd().getResponse().getWriter().print(tip);
					rwb.close();
					return; 
				}
				if(st.getCell(3, i).getContents() == null || "".equals(st.getCell(3, i).getContents().trim())){		//4级隐患类型,第3列
					tip = "Ⅳ级隐患 (第 " + (i + 1) +  "行 第 4 列) 不能为空.";
					getContextPvd().getResponse().getWriter().print(tip);
					rwb.close();
					return; 
				}
				if(st.getCell(4, i).getContents() == null || "".equals(st.getCell(4, i).getContents().trim())){		//自查内容，第4列
					tip = "自查标准具体描述 (第 " + (i + 1) +  "行 第 5 列) 不能为空.";
					getContextPvd().getResponse().getWriter().print(tip);
					rwb.close();
					return; 
				}
				
			}
			
			if(tip == null) {
				tip = "校验成功!";
					getContextPvd().getResponse().getWriter().print(tip);
					rwb.close();
					return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("zczb: ZczbBzhAction:save()异常："+e.getMessage());
		}
	}
	/**
	 * 修改保存
	 * @return
	 */
	public String save1(){
		try {
			TbUser user = (TbUser)this.contextPvd.getSessionAttr(Util.SESSION_ADMINUSER);
			if(null!=this.objId && this.objId.length()>0){
				TbZczbBzhTable tab = (TbZczbBzhTable)this.utilService.getObjectById(TbZczbBzhTable.class, Long.parseLong(this.objId));
				if(null!=tab){
					//先将原对应关系清除
					this.utilService.deleteBySql("update tb_corp_type t set t.hidden_tab_id='',t.hidden_tab_name='' where t.hidden_tab_id="+tab.getId());
					if(null!=this.objIds && this.objIds.length()>0){
						String[] arry = this.objIds.split(",");
						for(int i=0;i<arry.length;i++){
							TbCorpType type = (TbCorpType)this.utilService.getObjectById(TbCorpType.class, Long.parseLong(arry[i]));
							if(null!=type){
								type.setHiddenTabId(tab.getId());
								type.setHiddenTabName(tab.getTabName());
								this.utilService.update(type);
							}
						}
					}
					this.utilService.saveActionLog(user, "修改了自查自报标准，将对应企业类型修改为"+this.objIds);
					this.setTip("操作成功！");
					return this.list();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("zczb: ZczbBzhAction:save1()异常："+e.getMessage());
		}
		return ERROR;
	}
	
	/**
	 * 加载标准详细页面
	 * @return
	 */
	public String look(){
		try {
			this.setKeyWord(this.contextPvd.decodeAndEncode(this.keyWord));
			if(null!=this.objId && this.objId.length()>0){
				TbZczbBzhTable tab = (TbZczbBzhTable)this.utilService.getObjectById(TbZczbBzhTable.class, Long.parseLong(this.objId));
				if(null!=tab){
					this.setTab(tab);
					String tem = this.typeTreeInit().asXML();
					tem = tem.replaceAll("\\\"", "\\\\\"");
					tem = tem.replaceAll("\n", "");
					this.setItemXml(tem);
					this.setResult("bzh_look");
					return SUCCESS;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("zczb: ZczbBzhAction:look()异常："+e.getMessage());
		}
		return ERROR;
	}
	
	
	/**
	 * 标准查看
	 * @return
	 */
	public String info(){
		try {
			this.setKeyWord(this.contextPvd.decodeAndEncode(this.keyWord));
			if(null!=this.objId && this.objId.length()>0){
				TbZczbBzhTable tab = (TbZczbBzhTable)this.utilService.getObjectById(TbZczbBzhTable.class, Long.parseLong(this.objId));
				if(null!=tab){
					StringBuffer sbf = new StringBuffer("from TbZczbBzhInfoView t where 1=1 and t.tabId="+tab.getId()+" ");
					this.setTab(tab);
					if(null!=this.cType && this.cType.length()>0){
						if("1".equals(this.cType) || "2".equals(this.cType)){
							sbf.append(" and t.infoType1="+this.cType);
						}else{
							sbf.append(" and t.infoType2="+this.cType);
						}
					}
					sbf.append(" order by t.infoSort");
					this.setObjList((List)this.utilService.getHqlQuery(sbf.toString()));
					this.setResult("bzh_info");
					return SUCCESS;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("zczb: ZczbBzhAction:info()异常："+e.getMessage());
		}
		return ERROR;
	}
	
	/**
	 * 取得1、2级类型
	 * @return
	 */
	
	public Document typeTreeInit(){
		try {
			Document   document = DocumentHelper.createDocument();
			Element tree = document.addElement("tree");
			tree.addAttribute("id", "0");
			Element type1= tree.addElement("item");			
			type1.addAttribute("text","基础管理");
			type1.addAttribute("id", "1");
			type1.addAttribute("im0", "folderClosed.gif");
			type1.addAttribute("im1", "folderOpen.gif");
			type1.addAttribute("im2", "folderClosed.gif");
			
			Element type2= tree.addElement("item");			
			type2.addAttribute("text","现场管理");
			type2.addAttribute("id", "2");
			type2.addAttribute("im0", "folderClosed.gif");
			type2.addAttribute("im1", "folderOpen.gif");
			type2.addAttribute("im2", "folderClosed.gif");
			
			
			List allList = (List)this.utilService.getHqlQuery("from TbZczbBzhType t where 1=1 and t.typeGrade=2 order by t.typeSort");
			if(null!=allList && allList.size()>0){
				for(int i=0;i<allList.size();i++){
					TbZczbBzhType type = (TbZczbBzhType)allList.get(i);
					if("1".equals(type.getTypeParentId().toString())){
						Element main= type1.addElement("item");			
						main.addAttribute("text",type.getTypeName());
						main.addAttribute("id", type.getId().toString());
						main.addAttribute("im0", "folderClosed.gif");
						main.addAttribute("im1", "folderOpen.gif");
						main.addAttribute("im2", "folderClosed.gif");
					}else{
						Element main= type2.addElement("item");			
						main.addAttribute("text",type.getTypeName());
						main.addAttribute("id", type.getId().toString());
						main.addAttribute("im0", "folderClosed.gif");
						main.addAttribute("im1", "folderOpen.gif");
						main.addAttribute("im2", "folderClosed.gif");
					}
				}
			}
			return document;
		} catch (Exception e) {
			e.printStackTrace();
			Loggers.error("XzzfAction 中 checkItemInit()方法："+e.getMessage());
		}
		return null;
	}
	
	public String getQuaryHql(){
		StringBuilder urls = new StringBuilder("");
		StringBuilder hql = new StringBuilder(" where 1=1 ");
		String key = "";
		if(null!=this.keyWord && this.keyWord.length()>0){
			if(null!=this.getSearch() && "1".equals(this.getSearch())){
				key = this.getKeyWord().trim();
			}else{
				key = this.contextPvd.decode(this.getKeyWord());	
			}
			this.setKeyWord(key);
			hql.append(" and t.tabName like '%"+key+"%'");
			urls.append("keyWord="+this.contextPvd.encode(this.keyWord));
		}else{
			urls.append("keyWord=");
		}
		hql.append(" and t.isDele=0");
		this.setUrls(urls.toString());
		return hql.toString();
	}
	
	/**
	 * 取得一级类型id
	 * @param type1
	 * @return
	 */
	public String getType1(String type1){
		if("基础管理".equals(type1)){
			return "1";
		}else{
			return "2";
		}
	}

	public File getDbFile() {
		return dbFile;
	}

	public void setDbFile(File dbFile) {
		this.dbFile = dbFile;
	}

	public String getDbFileContentType() {
		return dbFileContentType;
	}

	public void setDbFileContentType(String dbFileContentType) {
		this.dbFileContentType = dbFileContentType;
	}

	public String getDbFileFileName() {
		return dbFileFileName;
	}

	public void setDbFileFileName(String dbFileFileName) {
		this.dbFileFileName = dbFileFileName;
	}

	public String getFileTypes() {
		return fileTypes;
	}

	public void setFileTypes(String fileTypes) {
		this.fileTypes = fileTypes;
	}

	public String getObjIds() {
		return objIds;
	}

	public void setObjIds(String objIds) {
		this.objIds = objIds;
	}

	public List getHaveList() {
		return haveList;
	}

	public void setHaveList(List haveList) {
		this.haveList = haveList;
	}

	public String getItemXml() {
		return itemXml;
	}

	public void setItemXml(String itemXml) {
		this.itemXml = itemXml;
	}

}
